﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Collections.ObjectModel;
using CPlatePrintSys.Application.Views;
using Prism.Commands;
using Prism.Mvvm;
using CPlatePrintSys.Domain.Models;
using CPlatePrintSys.Domain.Services;
using System.Windows.Input;
using CPlatePrintSys.Domain.Enums;
using Prism.Navigation.Regions;
using CPlatePrintSys.Domain.Events;
using Prism.Events;

namespace CPlatePrintSys.Application.ViewModels
{
    public class UserManagementViewModel : BindableBase, INavigationAware
    {
        private readonly IUserService _userService;
        private readonly IEventAggregator _eventAggregator;
        public ObservableCollection<User> Users { get; } = new ObservableCollection<User>();
        public DelegateCommand AddUserCommand { get; }
        public DelegateCommand<User> EditUserCommand { get; }
        public DelegateCommand<User> DeleteUserCommand { get; }
        private User _currentUser;

        public UserManagementViewModel(IUserService userService, IEventAggregator eventAggregator)
        {
            _userService = userService;
            _eventAggregator = eventAggregator;
            AddUserCommand = new DelegateCommand(OnAddUser);
            EditUserCommand = new DelegateCommand<User>(OnEditUser);
            DeleteUserCommand = new DelegateCommand<User>(OnDeleteUser);

            LoadUsersAsync();
        }

        private async void LoadUsersAsync()
        {
            var users = await _userService.GetAllUsersAsync();
            Users.Clear();
            foreach (var user in users)
            {
                Users.Add(user);
            }
        }

        private void OnAddUser()
        {
            if (!CanAddUser)
            {
                MessageBox.Show("无权限添加用户！", "权限不足", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            var viewModel = new UserAddOrEditViewModel(_userService, _currentUser);
            var dialog = new UserAddOrEditView();
            dialog.DataContext = viewModel;
            dialog.Owner = System.Windows.Application.Current.MainWindow;
            dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            var result = dialog.ShowDialog();
            if (result == true)
            {
                LoadUsersAsync();
            }
        }

        private void OnEditUser(User user)
        {
            if (user == null) return;
            if (!CanEditUser(user))
            {
                MessageBox.Show("无权限修改该用户！", "权限不足", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            var viewModel = new UserAddOrEditViewModel(_userService, user, _currentUser);
            var dialog = new UserAddOrEditView();
            dialog.DataContext = viewModel;
            dialog.Owner = System.Windows.Application.Current.MainWindow;
            dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            var result = dialog.ShowDialog();
            if (result == true)
            {
                LoadUsersAsync();
            }
        }

        private async void OnDeleteUser(User user)
        {
            if (user == null) return;
            if (!CanDeleteUser(user))
            {
                MessageBox.Show("无权限删除该用户！", "权限不足", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            var result = MessageBox.Show($"删除后将不可恢复，您确认删除该账号？", "确认删除", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
            if (result == MessageBoxResult.OK)
            {
                await _userService.DeleteUserAsync(user.Id);
                LoadUsersAsync();
            }
        }

        private void OnUserLoggedIn(User user)
        {
            SetCurrentUser(user);
        }

        public void SetCurrentUser(User user)
        {
            _currentUser = user;
            RaisePropertyChanged(nameof(CanAddUser));
        }

        public bool CanAddUser => _currentUser != null && (_currentUser.Role == UserRole.SuperAdmin || _currentUser.Role == UserRole.Admin);

        private bool CanEditUser(User target)
        {
            if (_currentUser == null) return false;
            
            if (_currentUser.Role == UserRole.SuperAdmin)
            {
                // 只能编辑超级用户自己，或编辑/创建/删除非超级用户
                return target.Role == UserRole.SuperAdmin ? _currentUser.Id == target.Id : true;
            }

            if (_currentUser.Role == UserRole.Admin)
            {
                // 管理员只能编辑自己和普通用户
                return target.Role == UserRole.User || _currentUser.Id == target.Id;
            }

            // 普通用户只能编辑自己
            return _currentUser.Id == target.Id;
        }

        private bool CanDeleteUser(User target)
        {
            if (_currentUser == null) return false;
            if (_currentUser.Role == UserRole.SuperAdmin)
            {
                // 只能删除非超级用户
                return target.Role != UserRole.SuperAdmin;
            }
            if (_currentUser.Role == UserRole.Admin)
            {
                // 只能删除普通用户
                return target.Role == UserRole.User;
            }
            return false;
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            // 检查是否有已登录的用户（通过事件传递）
            if (navigationContext.Parameters.ContainsKey("CurrentUser"))
            {
                var user = navigationContext.Parameters["CurrentUser"] as User;
                if (user != null)
                {
                    SetCurrentUser(user);
                }
            }
        }

        public bool IsNavigationTarget(NavigationContext navigationContext) => true;

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            // 取消订阅事件，避免内存泄漏
            _eventAggregator.GetEvent<UserLoggedInEvent>().Unsubscribe(OnUserLoggedIn);
        }
    }
}
